import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import AddBill from '../views/AddBill.vue'
import BillList from '../views/BillList.vue'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login,
  },
  {
    path: '/add',
    name: 'AddBill',
    component: AddBill,
    meta: { requiresAuth: true },
  },
  {
    path: '/bills',
    name: 'BillList',
    component: BillList,
    meta: { requiresAuth: true },
  },
  {
    path: '/charts',
    name: 'Charts',
    component: () => import('@/views/ChartView.vue'),
    meta: { requiresAuth: true },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫：拦截需要登录的页面
router.beforeEach((to, from, next) => {
  const userId = localStorage.getItem('user_id')
  if (to.meta.requiresAuth && !userId) {
    alert('请先登录')
    next({ path: '/' })
  } else {
    next()
  }
})

export default router
